import React from 'react'
import { Toast } from "antd-mobile";
import Html2Canvas from "html2canvas";

import './poster.less'

const bgImg = require("@/assets/imgs/poster.png");

export default class Login extends React.Component {

  state = {
    resultImg: ""
  }

  async componentDidMount() {
    this.getPosterImg()
  }

  posterHTML = React.createRef();

  isLoaded = false; // 图片加载完成

    // 3、生成海报图
    getPosterImg = async () => {
      let canvas, imageData, isTimeout;
      let loadInterval = null;
      Toast.loading("分享图生成中...", 20, () => {
        Toast.info("分享图生成超时~", 2);
        isTimeout = true;
        clearInterval(loadInterval);
        return;
      });
      // 等待图片加载完成
      await new Promise((resolve) => {
        loadInterval = setInterval(() => {
          if (this.isLoaded) {
            clearInterval(loadInterval);
            this.isLoaded = false;
            return resolve();
          }
        }, 1000);
      });
  
      canvas = await Html2Canvas( this.posterHTML.current, {
        // scale: window.devicePixelRatio,
        // scale: 1.5,
        scrollY: 0,
        scrollX: 0,
        allowTaint: true,
        useCORS: true, // 开启跨域配置
      });
      if (canvas && !isTimeout) {
        let imageType = "jpeg";
        imageData = canvas.toDataURL("image/" + imageType, 0.8);
        if (imageData.indexOf("base64") === -1) {
          Toast.info("生成分享图失败", 1.5);
          return "";
        }
  
        Toast.hide();
        this.setState({
          resultImg: imageData
        })
        console.log("imageData---", imageData)
      }
    };

  // 图片加载完成
  imgLoaded = () => {
    console.log("imgLoaded")
    this.isLoaded = true;
  };

  render () {
    const { resultImg } = this.state
    return (
      <div className="posterWrap">
        <div ref={this.posterHTML} className="posterWrapHide">
          <div className="bgImg">
            <img src={bgImg} alt="" onLoad={this.imgLoaded} />
          </div>
          <div>测试海波啊数据合成啊</div>
        </div>
        <div className="mask"></div>
        {this.resultImg !== "" && <div className="posterWrapTop">
          <div className="bgImg">
            <img src={resultImg} alt="" />
          </div>
        </div>}
      </div>
    )
  }
}
